import { Service } from 'egg';

export default class BindPhoneService extends Service {
    public async bindPhone(openid: string, username: string, phone: string) {
        const { ctx, service } = this;

        // 通过openId查找数据库中对应的用户
        let user = await service.db.user.findOneByOpenid(openid);
        // 如果用户已存在
        if (user) {
            this.ctx.helper.weixinBoundError();
        }

        user = await service.db.user.findOneByPhone(phone);
        if (user != null) {
            if (user.openid) {
                // 手机号已经绑定
                ctx.helper.phoneBoundError();
            }
            // 用于为预绑定用户，直接绑定openid
            await service.db.user.bindOpenid(user, openid);
        } else {
            await service.db.user.createByUser(openid, username, phone);
        }
    }
}
